<template>
  <div>
    <el-upload
      :action="useOss ? ossUploadUrl : minioUploadUrl"
      :data="useOss ? dataObj : null"
      list-type="picture"
      :multiple="false"
      :show-file-list="showFileList"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <template v-slot:tip>
        <div class="el-upload__tip">只能上传jpg/png文件，且不超过10MB</div>
      </template>
    </el-upload>
    <el-dialog v-model="dialogVisible">
      <img width="100%" :src="fileList[0].url" alt="" />
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { policy } from '@/api/oss'
import { computed, ref } from 'vue'

defineOptions({
  name: 'SingleUpload',
})
const props = defineProps({
  value: {
    type: String,
    default: '',
  },
})
const imageUrl = computed(() => {
  return props.value
})
const imageName = computed(() => {
  if (props.value != null && props.value !== '') {
    return props.value.substr(props.value.lastIndexOf('/') + 1)
  } else {
    return null
  }
})
const fileList = computed(() => {
  return [
    {
      name: imageName.value,
      url: imageUrl.value,
    },
  ]
})
const showFileList = computed({
  get: function () {
    return props.value !== null && props.value !== '' && props.value !== undefined
  },
  set: function (newValue) {},
})
const emit = defineEmits(['input'])
const dataObj = ref({
  policy: '',
  signature: '',
  key: '',
  ossaccessKeyId: '',
  dir: '',
  host: '',
  // callback:'',
})
const dialogVisible = ref(false)
const useOss = ref(false)
const ossUploadUrl = 'http://macro-oss.oss-cn-shenzhen.aliyuncs.com'
const minioUploadUrl = 'http://localhost:8080/minio/upload'

function emitInput(val) {
  emit('input', val)
}

function handleRemove(file, fileList) {
  emitInput('')
}

function handlePreview(file) {
  dialogVisible.value = true
}

function beforeUpload(file) {
  if (!useOss.value) {
    //不使用oss不需要获取策略
    return true
  }
  return new Promise((resolve, reject) => {
    policy().then((response) => {
      dataObj.value.policy = response.data.policy
      dataObj.value.signature = response.data.signature
      dataObj.value.ossaccessKeyId = response.data.accessKeyId
      dataObj.value.key = response.data.dir + '/${filename}'
      dataObj.value.dir = response.data.dir
      dataObj.value.host = response.data.host
      resolve(true)
    })
  })
}

function handleUploadSuccess(res, file) {
  showFileList.value = true
  fileList.value.pop()
  let url = dataObj.value.host + '/' + dataObj.value.dir + '/' + file.name
  if (!useOss.value) {
    //不使用oss直接获取图片路径
    url = res.data.url
  }
  fileList.value.push({ name: file.name, url: url })
  emitInput(fileList.value[0].url)
}
</script>
<style></style>
